package com.edu.framework.websocket.handler;

import com.alibaba.fastjson2.JSONException;
import com.edu.common.utils.StringUtils;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.auth.AuthRequest;
import com.edu.framework.websocket.message.base.Response;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;

@Component
public class AuthRequestHandler implements IHandler<AuthRequest> {

    @Override
    public void execute(WebSocketSession webSocketSession, AuthRequest message) {
        try {
            Map<String, String> data = message.getData();

            if (StringUtils.isEmpty(data.get(AuthRequest.RESP_KEY))) {
                String errmsg = "token未传入";
                Response<Object> response = Response.fail(AuthRequest.TYPE, errmsg);
                WebSocketHolder.send(webSocketSession, response);
                return;
            }
            Response<String> response = Response.ok(AuthRequest.TYPE, AuthRequest.RESP_KEY, "token-value");
            WebSocketHolder.send(webSocketSession, response);
        } catch (JSONException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getType() {
        return AuthRequest.TYPE;
    }
}
